package com.banciyuan.bcywebview.biz.write.write;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoreApi;
import com.banciyuan.bcywebview.api.DailyApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.MyProgressDialog;
import com.banciyuan.bcywebview.base.view.tag.FlowView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.detail.complex.ComplexDetailActivity;
import com.banciyuan.bcywebview.biz.groupdetail.AutoComplateAdapter;
import com.banciyuan.bcywebview.biz.post.auto.AutoComplateHelper;
import com.banciyuan.bcywebview.biz.post.auto.IGetAutoComplate;
import com.banciyuan.bcywebview.biz.post.succ.PostSuccActivity;
import com.banciyuan.bcywebview.biz.post.uploadpic.receiver.UploaderReceiver;
import com.banciyuan.bcywebview.biz.write.DailyRightsActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.model.PhotoModel;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.encrypt.MD5;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.banciyuan.bcywebview.utils.http.BcyPair;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.DiscoverTags;
import de.greenrobot.daoexample.model.FollowTag;
import de.greenrobot.daoexample.model.Multi;
import de.greenrobot.daoexample.model.PostItem;

/**
 * Created by squall on 2016/1/25.
 */
public class WriteTagActivity extends BaseActivity implements View.OnClickListener {

    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private TextView save_work;
    private FlowView tag_area;
    private FlowView add_retag_lv;
    private RelativeLayout top_line;
    protected AutoCompleteTextView auto_text;
    private TextView save_btn;
    private EditText tag_add_et;
    private TextView save_btn_gray;

    private List<String> pathList = new ArrayList<>();
    protected List<String> worklist = new ArrayList<>();
    private List<String> tlist = new ArrayList<>();

    private AutoComplateHelper autoComplateHelper;
    private AutoComplateAdapter autoComplateAdapter;
    private GetAutoComplate getAutoComplate;
    protected WriteHelper mHelper;
    private WriteInter writeInter;

    private Gson gson;
    protected String content;
    protected MyProgressDialog mDialog;
    private TextView tv_save;

    private String default_work;
    private String default_tag;
    private RequestQueue queue;
    private Set<String> mTagSet = new LinkedHashSet<>();
    private List<FollowTag> flist = new ArrayList<>();
    private LinkedList<String> mMemoryTagList = new LinkedList<>();
    public static final int GO_SETRIGHTS = 1000;
    protected PostItem.Authority mAuthority;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_group);
        initArgs();
        initActionbar();
        initUi();
        initAction();
        getComplateFirst();
        getRecommendTag();
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.edittag));
        mActionbarHelper.addItemOneText(getString(R.string.post));
        tv_save = (TextView) findViewById(R.id.base_action_bar_home_text_item);
        tv_save.setOnClickListener(this);
        mActionbarHelper.setActionCallbacks(new ActionbarHelper.OnActionCallbacks() {
            @Override
            public void onBackClick() {
                finishActivity();
            }

            @Override
            public void onActionClick(int id) {

            }
        });
    }

    private void finishActivity() {
        if (mDialog.isShowing()) {
            mDialog.dismiss();
        } else {
            Intent intent = new Intent();
            intent.putExtra("authority", mAuthority);
            setResult(RESULT_CANCELED, intent);
            finish();
        }
    }

    private void getRecommendTag() {
        String url = HttpUtils.BASE_URL + DailyApi.getDailyPostTags();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair("content", content));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, WriteTagActivity.this)) {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray result = jsonObject.getJSONArray(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        flist = gson.fromJson(result.toString(), new TypeToken<List<FollowTag>>() {
                        }.getType());
                        if (null != tlist) {
                            renderTags();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, this, null);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, params, onSucc, onErrorProxy);
        queue.add(param);
    }

    private void renderTags() {
        for (FollowTag discoverTags : flist) {
            mTagSet.add(discoverTags.getTag_name());
        }
        getDailyTagFromDiskMemory();
        addTagView();
    }

    private void getComplateFirst() {
        if (!TextUtils.isEmpty(default_work)) {
            String url = HttpUtils.BASE_URL + CoreApi.getGetcorelist();
            AutoComplateHelper autoHelper = new AutoComplateHelper(WriteTagActivity.this, getAutoComplate, "");
            autoHelper.findServerTitle(default_work, false, url);
        }
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(this);
        default_tag = getIntent().getStringExtra("tag");
        default_work = getIntent().getStringExtra("work");
        mAuthority = (PostItem.Authority) getIntent().getSerializableExtra("authority");
        gson = new Gson();
        autoComplateHelper = new AutoComplateHelper(WriteTagActivity.this, getAutoComplate, "work");
        getAutoComplate = new GetAutoComplate();
        writeInter = new WriteInter();
        mHelper = new WriteHelper(WriteTagActivity.this, writeInter);
        content = getIntent().getStringExtra("content");
        pathList = (List<String>) getIntent().getSerializableExtra("pathList");
    }

    @Override
    protected void initUi() {
        save_work = (TextView) findViewById(R.id.acg_group_save);
        tag_area = (FlowView) findViewById(R.id.add_tag_lv);
        auto_text = (AutoCompleteTextView) findViewById(R.id.edit_group_autotv);
        top_line = (RelativeLayout) findViewById(R.id.linearLayout);
        save_btn = (TextView) findViewById(R.id.tag_group_add);
        tag_add_et = (EditText) findViewById(R.id.tag_add_et);
        save_btn_gray = (TextView) findViewById(R.id.acg_group_save_vaild);
        add_retag_lv = (FlowView) findViewById(R.id.add_retag_lv);
        add_retag_lv.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(default_work)) {
            auto_text.setText(default_work);
        }
        if (!TextUtils.isEmpty(default_tag)) {
            tag_add_et.setText(default_tag);
            addTagFun(tag_add_et);
        }
        DialogInterface.OnClickListener cancelOnClick = null;
        DialogInterface.OnCancelListener onCancelClick = null;
        cancelOnClick = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mDialog.dismiss();
            }
        };
        MyProgressDialog.Builder mBuilder = new MyProgressDialog.Builder(this);
        mDialog = mBuilder.setCancelButton(cancelOnClick).setOnCancelButton(onCancelClick).create();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_action_bar_home_text_item:
                beginPost();
                break;
            case R.id.tag_group_add:
                addTagFun(tag_add_et);
                break;
            case R.id.ll_rights_set:
                Intent intent = new Intent(this, DailyRightsActivity.class);
                intent.putExtra("authority", mAuthority);
                startActivityForResult(intent, GO_SETRIGHTS);
                break;
        }
    }

    private void addTagFun(View view) {
        String label = "";
        if (view.getId() == R.id.tag_add_et) {
            label = tag_add_et.getText().toString().trim();
            if (TextUtils.isEmpty(label)) {
                MyToast.show(WriteTagActivity.this, getString(R.string.label_shoudnot_benull));
                return;
            }
        } else {
            label = ((TextView) view).getText().toString();
        }
        if (auto_text.getText().toString().equals(label)) {
            MyToast.show(WriteTagActivity.this, getString(R.string.same_work_and_tag));
            return;
        }
        if (tlist.contains(label)) {
            MyToast.show(WriteTagActivity.this, getString(R.string.label_mutli_disable));
            return;
        } else {
            if (tlist.size() < 3) {
                tlist.add(label);
            } else {
                MyToast.show(WriteTagActivity.this, getString(R.string.label_three_limit));
                return;
            }
        }
        if (tag_area.getVisibility() == View.GONE) {
            tag_area.setVisibility(View.VISIBLE);
        }

        View viewcancel = View.inflate(WriteTagActivity.this, R.layout.tag_blue_cancel, null);
        TextView textview = (TextView) viewcancel.findViewById(R.id.single_tag_cancel);
        textview.setText(label);
        tag_area.addView(viewcancel);
        viewcancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tag_area.removeView(view);
                TextView cancel_label = (TextView) view.findViewById(R.id.single_tag_cancel);
                tlist.remove(cancel_label.getText().toString());
                if (tag_area.getChildCount() == 0) {
                    tag_area.setVisibility(View.GONE);
                }
            }
        });

        tag_add_et.setText("");
    }

    private class GetAutoComplate implements IGetAutoComplate {

        @Override
        public void getComplateList(String s, boolean show) {
            dealAutoJson(s, show);
        }
    }

    private void dealAutoJson(String s, boolean show) {
        try {
            if (StatusCodeUtils.dealStatusCode(s, this)) {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                worklist.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    worklist.add(jsonArray.getString(i));
                }
                autoComplateAdapter = new AutoComplateAdapter(worklist, this, auto_text.getText().toString());
                auto_text.setAdapter(autoComplateAdapter);
            }
            if (show) {
                if (!this.isFinishing()) {
                    auto_text.showDropDown();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initAction() {
        auto_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!auto_text.isPerformingCompletion()) {
                    if (!TextUtils.isEmpty(s.toString())) {
                        String url = HttpUtils.BASE_URL + CoreApi.getGetcorelist();
                        AutoComplateHelper autoHelper = new AutoComplateHelper(WriteTagActivity.this, getAutoComplate, "");
                        autoHelper.findServerTitle(s, true, url);
                    }
                    if (TextUtils.isEmpty(s.toString())) {
                        auto_text.dismissDropDown();
                    }
                }
            }
        });

        tag_add_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    addTagFun(tag_add_et);
                }
                return true;
            }
        });

        save_btn.setOnClickListener(this);
        View viewRightSet = findViewById(R.id.ll_rights_set);
        viewRightSet.setVisibility(View.VISIBLE);
        viewRightSet.setOnClickListener(this);
    }

    private class WriteInter implements IWriteInter {

        @Override
        public void writeSucc(String json) {
            try {
                JSONObject jsonObject = new JSONObject(json);
                String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                pushSuccess(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void writeFail(String json) {
            mDialog.dismiss();
        }
    }

    public void pushSuccess(String dataId) {
        if (!WriteTagActivity.this.isFinishing()) {
            mDialog.dismiss();
        }

        Intent intent = new Intent();
        intent.setClass(this, ComplexDetailActivity.class);
        intent.putExtra(MyConstants.UDIDVALUE, dataId);
        intent.putExtra(MyConstants.TIMELINETYPE, TimelineFactory.TIMELINE_TYPE_DAILY);
        startActivityForResult(intent, WriteActivity.WRITE_ACTIVITY);

        DetailType detailType = new DetailType();
        detailType.setUd_id(dataId);
        detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_DAILY);
        Intent succ = new Intent(this, PostSuccActivity.class);
        succ.putExtra("detailtype", detailType);
        startActivity(succ);
    }

    protected void beginPost() {
        if (!isFinishing()) {
            mDialog.show();
            if (pathList != null && !pathList.isEmpty()) {
                mHelper.doPush("daily", "", pathList, content, auto_text.getText().toString(), gson.toJson(tlist), gson.toJson(mAuthority));
            } else {
                mHelper.doPush("daily", "", null, content, auto_text.getText().toString(), gson.toJson(tlist), gson.toJson(mAuthority));
            }
        }
        saveDailyTagInDiskMemory();
    }

    private void getDailyTagFromDiskMemory() {
        Gson gson = new Gson();
        String tagStr = SPHelper.getString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), SPConstant.DAILYTAG, "[]");
        mMemoryTagList = gson.fromJson(tagStr, new TypeToken<LinkedList<String>>() {
        }.getType());
        mTagSet.addAll(mMemoryTagList);
    }

    private void saveDailyTagInDiskMemory() {
        Gson gson = new Gson();
        mMemoryTagList.addAll(0, tlist);
        while (mMemoryTagList.size() > 10) {
            mMemoryTagList.removeLast();
        }
        String tagStr = gson.toJson(new LinkedHashSet<>(mMemoryTagList));
        SPHelper.putString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), SPConstant.DAILYTAG, tagStr);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == WriteActivity.WRITE_ACTIVITY) {
            setResult(WriteActivity.RESULT_OK, new Intent());
            finish();
        }
        if (requestCode == GO_SETRIGHTS) {
            mAuthority = (PostItem.Authority) data.getSerializableExtra("authority");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_BACK:
                finishActivity();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void addTagView() {
        add_retag_lv.removeAllViews();
        for (String tagName : mTagSet) {
            View view = View.inflate(WriteTagActivity.this, R.layout.tag_nomargin_blue, null);
            TextView textview = (TextView) view.findViewById(R.id.single_tag);
            textview.setText(tagName);
            final int index = add_retag_lv.getChildCount();
            textview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TextView tv = (TextView) v;
                    String key = tv.getText().toString();
                    addChildTag(key, index);
                    addTagFun(v);
                }
            });
            add_retag_lv.addView(view);
        }
    }

    private void addChildTag(String key, int index) {
        for (FollowTag f : flist) {
            if (key.equals(f.getTag_name())) {
                if (f.getRela_tags() != null && !f.getRela_tags().isEmpty()) {
                    Set<String> tempSet = new LinkedHashSet<>();
                    for (FollowTag discoverTags : f.getRela_tags()) {
                        tempSet.add(discoverTags.getTag_name());
                    }
                    tempSet.removeAll(mTagSet);
                    mTagSet.addAll(tempSet);
                    for (String tagName : tempSet) {
                        View view = View.inflate(WriteTagActivity.this, R.layout.tag_nomargin_blue, null);
                        TextView textview = (TextView) view.findViewById(R.id.single_tag);
                        textview.setText(tagName);
                        textview.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                addTagFun(v);
                            }
                        });
                        add_retag_lv.addView(view, index + 1);
                    }
                    break;
                }
            }
        }
    }
}
